/**
 * Created by Administrator on 2016/7/15.
 */
(function () {
	'use strict';

	angular
		.module('client')
		.factory('logcatService', logcatService);

	logcatService.$inject = ['$log', '$timeout', '$websocket', '$uibModal', 'LOGCAT_WS_API'];
	function logcatService($log, $timeout, $websocket, $uibModal , LOGCAT_WS_API) {
		var services = {
			openWs: openWs,
			closeWs: closeWs,
			clearLogcatState: clearLogcatState,
			changeLevel: changeLevel,
			isMac: isMac,
			formatLogcatData: formatLogcatData,
			exportLogcatData: exportLogcatData,
		};
		return services;

		var logWs;
		function openWs(uuid, logs, fliter) {
			logWs = $websocket(LOGCAT_WS_API.logcat);
			logWs._enable = true;
			logWs.onOpen(function () {
				logWs.send({uuid: uuid});
				changeLevel(fliter);
				$log.debug('open logcat ws');
			});

			var logcatList = [];
			logWs.onMessage(function (message) {
				var messageJson = angular.fromJson(message.data);
				var temp;
				logcatList = logcatList.concat(messageJson.data);
				while (logcatList.length) {
					temp = logcatList.shift();
					if (logs.unshift(temp) > 100) {
						logs.pop();
					}
				}
			});
			logWs.onClose(function (event) {
				$log.debug('logcat websocket was closed');
				logWs = undefined;
			});
		}

		function closeWs() {
			if(logWs) {
				logWs.close();
				$log.debug("close logcat ws");
			}
		}

		function clearLogcatState(logs) {

			if(angular.isArray(logs) ) {
				logs.length = 0;
				$log.debug('clear logcat data');
			}
		}

		function changeLevel(level, logs) {
			clearLogcatState(logs);
			if(logWs) {
				logWs.send({level: level});
			}
		}

		function isMac() {
			return /macintosh|mac os x/i.test(navigator.userAgent);
		}

		function formatLogcatData(logs, level) {
			var i;
			var item;
			var attr;
			var str = '\ufeff';
			var itemStr;
			var blob;
			var csvUrl;
			var fileName = 'logcat_';
			var date = new Date();
			var time = date.toTimeString().match(/\d+\:\d+\:\d+\S/g)[0];
			for(i = 0;i < logs.length; i ++){
				item = logs[i];
				itemStr = '';
				for(attr in item) {
					itemStr += item[attr] + ',  ';
				}
				str += itemStr + '\n';
			}
			blob = new Blob([str], { type: 'text/csv,charset=UTF-8'});

			csvUrl = URL.createObjectURL(blob);
			switch(level) {
				case '0': fileName += 'Info';
					break;
				case '1': fileName += 'Warn';
					break;
				case '2': fileName += 'Error';
					break;
				default: fileName += 'Info';
					break;
			}
			fileName += '日志 ' + date.toLocaleDateString() + ' ' + time;
			return {
				csvUrl: csvUrl,
				fileName: fileName,
			}
		}

		function exportLogcatData(logs, level) {
			var data = formatLogcatData(logs, level);
			var modal;
			modal = $uibModal.open({
				templateUrl: 'app/control/logcat/export/export.html',
				controller: 'ExportController',
				controllerAs: 'vm',
				size: 'md',
				resolve: {
					exportInfo: {
						url: data.csvUrl,
						fileName: data.fileName,
					}
				}
			});

			modal.result.then(function () {
				$log.info('download success');
			}, function (error) {
				$log.error('download failed');
			});

		}

	}
})();
